﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Networking
{
    /// <summary>
    /// Packet of type ProtocolVersion, the first packet in VNC handshaking
    /// </summary>
    public class ProtocolVersionPacket : Packet
    {

        /// <summary>
        /// The requested protocol version
        /// </summary>
        public string Version { get; private set; }

        /// <summary>
        /// Creates a new instance of PacketProtocolVersion requesting a specified protocol version
        /// </summary>
        /// <param name="Version">The specified protocol version requested</param>
        public ProtocolVersionPacket(string Version) : base(PacketType.ProtocolVersion)
        {
            this.Version = Version;
        }

        public ProtocolVersionPacket(byte[] buffer)
            : base(PacketType.ProtocolVersion, buffer)
        {
            //
        }

        /// <summary>
        /// Serializes the packet in order to send it
        /// </summary>
        /// <returns>The bytes of the packet</returns>
        public override byte[] Serialize()
        {
            return Encoding.ASCII.GetBytes("IVC " + this.Version + '\n');
        }
        

        /// <summary>
        /// Loads a packet from a byte buffer
        /// </summary>
        /// <param name="buffer">The data buffer</param>
        public override void Load(byte[] buffer)
        {
            string sTemp = Encoding.ASCII.GetString(buffer);

            if (!sTemp.Contains("IVC "))
                throw new CorruptedPacketException(PacketType.ProtocolVersion, "IVC not present");

            //if (sTemp[sTemp.Length - 1] != '\n')
            //    throw new CorruptedPacketException(PacketType.ProtocolVersion, "End line char not present");

            Version = sTemp.Remove(0, 4).Trim();

        }
    }
}
